package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.GuliESConfig;
import com.atguigu.gulimall.search.constant.EscConstant;
import com.atguigu.gulimall.search.service.MallSearchSevice;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchReslut;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MallSearchSeviceImpl implements MallSearchSevice {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public SearchReslut querySearch(SearchParam param) {

        SearchReslut reslut = null;
        //准备检索请求
        SearchRequest searchRequest = builSearchRequest(param);

        try {
            //2、执行检索请求
            SearchResponse response = client.search(searchRequest, GuliESConfig.COMMON_OPTIONS);
            //3、分析响应数据封装成需要的格式
            reslut = builSearchReslut(response,param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return reslut;
    }


    //动态构建需要查询的DSL语句
    //准备检索请求
    private SearchRequest builSearchRequest(SearchParam param) {
        //动态构建需要查询的DSL语句
        SearchSourceBuilder builder = new SearchSourceBuilder();
        /**
         * 模糊匹配，过滤（属性、分类、品牌、价格区间、库存）
         */
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //1、1 must模糊匹配
        if (StringUtils.isNotEmpty(param.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        //1、2 bool- filter过滤按3级分类id查询
        if (param.getCatalog3Id() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        //1、2  bool- filter按品牌id查询
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        //1、2  bool- filter按所有指定的属性
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {

            for (String attr : param.getAttrs()) {
                BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                String attrId = s[0];//属性id
                String[] attrValues = s[1].split(":");//属性值
                boolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                boolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                NestedQueryBuilder nestedQuery=QueryBuilders.nestedQuery("attrs",boolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);
            }

        }
        //1、2  bool- filter按是否有库存
        if (param.getHasStock()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1 ? true : false));
        }

        //1、2  bool- filter按价格区间
        if (StringUtils.isNotEmpty(param.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2) {
                if (StringUtils.isNotEmpty(s[0])){
                    rangeQuery.gte(s[0]).lte(s[1]);
                }else {
                    rangeQuery.lte(s[1]);
                }

            } else {
                rangeQuery.gte(s[0]);
            }

            boolQueryBuilder.filter(rangeQuery);
        }
        builder.query(boolQueryBuilder);
        /**
         * 排序、分页、高亮
         */
        //2、1排序
        if (StringUtils.isNotEmpty(param.getSort())){
            String sort=param.getSort();
            String[] s = sort.split("_");
            SortOrder order=s[1].equalsIgnoreCase("asc")?SortOrder.ASC:SortOrder.DESC;
            builder.sort(s[0],order);
        }
        //2、2分页
        builder.from( (param.getPageNum()-1)*EscConstant.PAGE_SIZE );
        builder.size(EscConstant.PAGE_SIZE);
       //2、3高亮
        if (StringUtils.isNotEmpty(param.getKeyword())){
            HighlightBuilder highlightBuilder=new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            builder.highlighter(highlightBuilder);
        }

        /**
         * 聚合分析
         */
        //1、品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        //品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        builder.aggregation(brand_agg);

        //分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
        catalog_agg.field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalogId_name_agg").field("catalogName").size(1));
        builder.aggregation(catalog_agg);
       //属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        builder.aggregation(attr_agg);
        SearchRequest request = new SearchRequest(new String[]{EscConstant.PRODUCT_INDEX}, builder);
        System.out.println(builder.toString());
        return request;
    }

    //分析响应数据封装成需要的格式
    private SearchReslut builSearchReslut(SearchResponse response, SearchParam param) {
        SearchReslut reslut = new SearchReslut();


        //1、返回所有查询到的商品
        SearchHits hits = response.getHits();
        List<SkuEsModel> esModels=new ArrayList<>();
        if (hits.getHits()!=null&&hits.getHits().length>0){
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel sku =JSON.parseObject(sourceAsString,SkuEsModel.class);
                if (StringUtils.isNotEmpty(param.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String s = skuTitle.getFragments()[0].string();
                    sku.setSkuTitle(s);
                }
                esModels.add(sku);
            }
        }
        reslut.setProducts(esModels);
       //2、分页
        //当前页
        reslut.setPageNum(param.getPageNum());
       //总记录数
        long total = hits.getTotalHits().value;
        reslut.setTotal(total);
        //总页数
       int totalPagees= (int) (total%EscConstant.PAGE_SIZE==0?total/EscConstant.PAGE_SIZE:total/EscConstant.PAGE_SIZE+1);
        reslut.setTotalPagees(totalPagees);
        //3、所有品牌信息
        List<SearchReslut.Brandvo> brandvos=new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchReslut.Brandvo brandvo=new SearchReslut.Brandvo();
            //品牌id
            Long brandId = (Long) bucket.getKey();
            brandvo.setBrandId(brandId);
            //得到品牌图片
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brandLogo = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandvo.setBrandLogo(brandLogo);
            //得到品牌名
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandvo.setBrandName(brandName);
            brandvos.add(brandvo);

        }
        reslut.setBrands(brandvos);
        //4、商品属性信息
        List<SearchReslut.attrVo> attrVos=new ArrayList<>();
        ParsedNested attr_agg= response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchReslut.attrVo attrVo = new SearchReslut.attrVo();
            //属性id
            Long attrId = (Long) bucket.getKey();
            //属性名
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attrNmae = attr_name_agg.getBuckets().get(0).getKeyAsString();
            //属性值
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValues = attr_value_agg.getBuckets().stream().map(item -> {
                String keyAsString = item.getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            attrVo.setAttrId(attrId);
            attrVo.setAttrNmae(attrNmae);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }

        reslut.setAttrs(attrVos);
       //5、分类
        List<SearchReslut.catelogVo> catelogVos=new ArrayList<>();
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            SearchReslut.catelogVo catelogVo=new SearchReslut.catelogVo();
            //得到分类id;
           Long  key = (Long) bucket.getKey();
           catelogVo.setCatelogId(key);
           //得到分类名
            ParsedStringTerms catalogId_name_agg = bucket.getAggregations().get("catalogId_name_agg");
            String catelogName = catalogId_name_agg.getBuckets().get(0).getKeyAsString();
            catelogVo.setCatelogNmae(catelogName);
           catelogVos.add(catelogVo);

        }
        reslut.setCatelogs(catelogVos);
        return reslut;
    }
}
